import { Spin } from "antd";
import React from "react";
import { TOKEN } from "./constants";
import Https2 from "./utils/Https2";
import { getItem } from "./utils/localstorage";
interface RouteItem {
  path?: string;
  name?: string;
  icon?: string;
  id?: number | string;
  parentId?: number | string;
  element?: JSX.Element;
  children?: RouteItem[];
}

let extraRoutes: any[] = [];
const loopMenuItem = (menus: any): RouteItem[] => {
  return menus.flatMap((item) => {
    let Component: React.ComponentType<any> | null = null;
    if (item.component) {
      // 防止配置了路由，但本地暂未添加对应的页面，产生的错误
      Component = React.lazy(
        () =>
          new Promise((resolve, reject) => {
            import(`@/pages/${item.component}`)
              .then((module) => resolve(module))
              .catch((error) => resolve(import(`@/pages/404`)));
          })
      );
    }
    if (item.children) {
      return [
        {
          path: item.path,
          name: item.name,
          children: [...loopMenuItem(item.children)],
        },
      ];
    } else {
      return [
        {
          path: item.path,
          name: item.name,
          element: (
            <React.Suspense
            // fallback={<Spin />}
            >
              {Component && <Component />}
            </React.Suspense>
          ),
        },
      ];
    }
  });
};
export function patchClientRoutes({ routes }) {
  const routerIndex = routes.findIndex((item: RouteItem) => item.path === "/");
  let Component1: React.ComponentType<any> | null = null;
  // 防止配置了路由，但本地暂未添加对应的页面，产生的错误
  Component1 = React.lazy(
    () =>
      new Promise((resolve, reject) => {
        import(`@/layouts/BasicLayout`)
          .then((module) => resolve(module))
          .catch((error) => resolve(import(`@/pages/404/index`)));
      })
  );
  if (extraRoutes && extraRoutes.length > 0) {
    routes[routerIndex]["routes"].push({
      path: "/",
      element: (
        <React.Suspense fallback={<Spin />}>
          {Component1 && <Component1 />}
        </React.Suspense>
      ),
      children: [...loopMenuItem(extraRoutes)],
    });
  }
}

export async function render(oldRender: () => void) {
  var userAgent = navigator.userAgent.toLowerCase();
  if (/ipad|iphone|android/.test(userAgent)) {
    console.log("手机");
  } else {
    if (!getItem(TOKEN)) {
      if (window.location.pathname.includes("user")) {
        oldRender();
        return;
      } else {
        window.location.replace("/user/login");
      }
    } else {
      let objRoutes = [
        {
          path: "*",
          component: "404/index",
        },
        {
          path: "/welcome",
          component: "welcome",
        },
        {
          path: "/stadium/selectVenue",
          component: "stadium/list/selectVenue",
        },
      ];
      let res: any = await Https2.get("/system/menu/getRouters", {}, true);
      if (res.code == 200 && res.data) {
        if (res.data.length > 0) {
          res.data.map((item) => {
            objRoutes.push(item);
          });
        }
      }
      extraRoutes = objRoutes;
      oldRender();
    }
  }
}
